package com.example.armmvvm.ui.fallview

import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import com.google.android.material.bottomsheet.BottomSheetBehavior

/**
 * author : yanghaozhang
 * date : 2022/10/18 19:01
 * description :
 */
internal class BehaviorLieScroll {

    companion object{
        /**
         * 欺骗性下滑,目的是避免FallView切换,高->矮时,没有更新界面,底部留白
         * 缺点,界面上必须有NestedScrollingChild
         * @return
         */
        fun <V : View> lieScrollRefresh(behavior: BottomSheetBehavior<V>, viewContainer: View): Boolean {
            if (viewContainer.parent is CoordinatorLayout) {
                val scrollingChild = findScrollingChild(viewContainer)
                if (scrollingChild != null) {
                    behavior.onNestedPreScroll(
                        (viewContainer.parent as CoordinatorLayout),
                        viewContainer as V,
                        scrollingChild,
                        0,
                        -1,
                        IntArray(2),
                        ViewCompat.TYPE_TOUCH
                    )
                    return true
                }
            }
            return false
        }

        private fun findScrollingChild(view: View?): View? {
            view ?: return null
            if (ViewCompat.isNestedScrollingEnabled(view)) {
                return view
            }
            if (view is ViewGroup) {
                var i = 0
                val count = view.childCount
                while (i < count) {
                    val childAt = view.getChildAt(i) ?: break
                    val scrollingChild = findScrollingChild(childAt)
                    if (scrollingChild != null) {
                        return scrollingChild
                    }
                    i++
                }
            }
            return null
        }
    }
}